package TAIC.Google ;
import java.io.*;
import java.util.* ;
import java.net.* ;
//    Total Image:  <span id=maxLimit>   </span>
//    Specific Image:  After 7th " of dyn.Img( )
//    Search for medium image http://images.google.com/images?q=pencil+box&gbv=2&svnum=10&hl=en&newwindow=1&imgsz=small|medium|large|xlarge&as_filetype=jpg
//    Search for all image:  http://images.google.com/images?hl=en&q=pencil+box&gbv=2&imgtype=photo
//    http://images.google.com/images?q=pencil+box&imgsz=small%7Cmedium%7Clarge%7Cxlarge&gbv=2&svnum=10&hl=en&newwindow=1&start=18&sa=N&ndsp=18&as_filetype=jpg
//    <font size=-1>Results

public class GImage implements Runnable {
    StringBuffer str = null ;  
    String line;
	Socket s  = null;
	int tPage = 0 ;
	String queryWord ; 
	String [] output = null ; // store result for run () 
	
	public GImage ( ){}
	public GImage ( int totalPages , String query ) {
		tPage = totalPages ;
		queryWord = query ; 
	}
	
	public String [] getResult () {
		return output ;
	}
	
	public void run () {
		output = getImages ( tPage, queryWord ) ; 
	}
	
    static public void main ( String agu [] ){
		String [] s =  (new GImage()).getImages( 20 , "pencil box" ) ;
		for ( int i = 0; i < s.length ; i ++ ) System.out.println ( i + " " + s [ i ] ) ; 
    }
	
	public Long getImageCount ( String query ) {
		int i ;
		String q ; 
		q = query.trim().replace ( " " , "+" ); 
        BufferedReader buffer = null;
        str = new StringBuffer ();
        str.ensureCapacity( 40000 ) ;      
		
		for ( i = 0 ; i < 10 ; i ++ )
		try {
			s = new Socket("image.google.com",80);        
            s.setSoTimeout( 10000 ) ;
        	PrintStream p = new PrintStream( s.getOutputStream() );
        	p.print( "GET /images?hl=en&q=" + q + "&gbv=1\r\n" );
            InputStreamReader in = new InputStreamReader(s.getInputStream());
			buffer = new BufferedReader(in);
            while ((line = buffer.readLine()) != null) str.append ( line ) ;
            in.close();
			s.close ();
			break ; 
		}
		catch ( Exception e ) {
			System.out.println ( "Google Image Search for query \"" + query + "\" fails for the " + ( i+ 1) + "th time." );
		}
		if ( i >= 10 ) {
			System.out.println ( "Google Image Search Failed for query \"" + query + "\"" ) ;
			return (long)0 ; 
		} else { 
			int index1 , index2 ; 
			index1 = str.indexOf ( "<span id=maxLimit>" ) ;
			index2 = str.indexOf ( "</span>" , index1 ) ; 
			if ( index1 == -1 ) return ( long ) 0 ; 
			else return Long.valueOf ( str.substring ( index1 + 18 , index2 ).replace ( "," , "" )) ;
		}
	}

	public String  [] getImages ( int totalPages , String query ) {
		String result[] = new String [ totalPages ] ;
		String aPage []  ;
		int i ,j ;
		
		for ( i = 0 ; i <= Math.floor ((double)(totalPages-1)/18) ; i ++ ) {
			aPage = getAPage ( i , query ) ;
			for ( j = 0 ; j < aPage.length ; j ++ ) 
				if ( i * 18 + j < totalPages ) result [ i * 18 + j ] = aPage [ j ] ; 
		}	
		return result ; 
	}
	
	private String [] getAPage ( int pageNo , String query ) {
		int i ;
		String q ; 
		q = query.trim().replace ( " " , "+" ); 
        BufferedReader buffer = null;
        str = new StringBuffer ();
        str.ensureCapacity( 40000 ) ;      
		
		for ( i = 0 ; i < 10 ; i ++ )
		try {
			s = new Socket("image.google.com",80);        
            s.setSoTimeout( 10000 ) ;
        	PrintStream p = new PrintStream( s.getOutputStream() );
        	p.print( "GET /images?as_q=" + q + "&hl=en&start="+18*pageNo+"&sa=N&ndsp=18&as_filetype=jpg\r\n" );
            InputStreamReader in = new InputStreamReader(s.getInputStream());
			buffer = new BufferedReader(in);
            while ((line = buffer.readLine()) != null) str.append ( line ) ;
            in.close();
			s.close ();
			break ; 
		}
		catch ( Exception e ) {
			System.out.println ( "Google Image Search for query \"" + query + "\" fails for the " + ( i + 1 ) + "th time." );
		}
		if ( i >= 10 ) {
			System.out.println ( "Google Image Search Failed for query \"" + query + "\"" ) ;
			return null ; 
		} else { 
			String [] result = new String [ 18 ] ; 
			int index1 = 0 , index2 = 0 ; 
			int temp , j; 
			
			for ( i = 0 ; i < 18 ; i ++ ) {
				temp = 0 ; 
				for ( j = str.indexOf ( "dyn.Img(" , index1 ) ; temp < 8 ; j ++ ) {
					if ( j == -1 ) {
						result [ i ] = "http://afadf.df.com" ;
						continue ;
					}
					if ( str.charAt ( j ) == '"' ) {
						temp ++ ;
						if ( temp == 7 ) index1 = j ;
						else if ( temp == 8 ) index2 = j ; 
					}
				}
				result [ i ] = str.substring ( index1 + 1 , index2 ) ;
			}
			return result ;
		}
	}
}
